/*
 * Copyright (c) 2006, 2023, webrx.cn All rights reserved.
 *
 */
package cn.webrx.config;

import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * <p></p>
 * <p>Powered by webrx On 2023-04-25 11:21:16</p>
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
@Configuration
@MapperScan("cn.webrx.mapper")
@ComponentScan("cn.webrx")
//@Import(MybaitsConfig.class)
@PropertySource("classpath:db.properties")
public class AppConfig {
    @Value("${db.driver}")
    private String driver;
    @Value("${db.url}")
    private String url;
    @Value("${db.username}")
    private String username;
    @Value("${db.password}")
    private String password;

    @Bean(name = "ds", destroyMethod = "close")
    public HikariDataSource hikariDataSource() {
        HikariDataSource ds = new HikariDataSource();
        ds.setPassword(password);
        ds.setUsername(username);
        ds.setJdbcUrl(url);
        ds.setDriverClassName(driver);
        return ds;
    }

    @Bean(name = "sf")
    public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean(DataSource ds) throws IOException {
        MybatisSqlSessionFactoryBean sf = new MybatisSqlSessionFactoryBean();
        sf.setDataSource(ds);

        GlobalConfig cc = new GlobalConfig();
        cc.setBanner(false);
        sf.setGlobalConfig(cc);

        PathMatchingResourcePatternResolver path = new PathMatchingResourcePatternResolver();
        sf.setMapperLocations(path.getResources("classpath:mapper/*.xml"));
        return sf;
    }

    @Bean
    public SqlSession sqlSession(SqlSessionFactory sf) {
        SqlSessionTemplate ss = new SqlSessionTemplate(sf);
        return ss;
    }


}
